'use strict';
const fs = require('fs');
const crypto = require('crypto');
const path = require('path');
// const config = require('./config');
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/pay/pub/paysignature 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			recharge_amount,
			outOrderNo,
			appId
		} = data;
		let res = {
			code: 0,
			msg: ""
		};





		function getByteAuthorization(privateKeyStr, datam, appId, nonceStr, timestamp, keyVersion) {
			try {
				// 生成签名
				const signature = getSignature(privateKeyStr, "POST", "/requestOrder", timestamp, nonceStr,
					datam);
				// 构造byteAuthorization
				const byteAuthorization =
					`SHA256-RSA2048 appid=${appId},nonce_str=${nonceStr},timestamp=${timestamp},key_version=${keyVersion},signature=${signature}`;
				return byteAuthorization;
			} catch (ex) {
				console.error(ex);
				return "";
			}
		}

		function getSignature(privateKeyStr, method, uri, timestamp, nonce, datam) {
			const rawStr = `${method}\n${uri}\n${timestamp}\n${nonce}\n${datam}\n`;

			const sign = crypto.createSign('RSA-SHA256');
			sign.update(rawStr, 'utf8');

			const privateKey = fs.readFileSync(privateKeyStr,
				'utf8'); // Assuming the private key is stored in a file

			// const signature = sign.sign(privateKey, 'base64');
			const signature = sign.sign({
				key: privateKey,
				format: 'pem',
				type: 'pkcs8'
			}, 'base64');
			return signature;
		}

		// 请求时间戳
		const timestamp = Math.floor(Date.now() / 1000);
		// 开发者填入自己的小程序app_id
		// const appId = "tt4bb03d0dd48249b101";
		// 随机字符串
		const nonceStr = require('crypto').randomBytes(16).toString('hex');
		// 应用公钥版本,每次重新上传公钥后需要更新
		const keyVersion = "2";
		// 应用私钥文件路径，请将路径替换为实际文件路径
		const privateKeyPath = path.join(__dirname, 'private_key.pem')

		console.log("获取参数", recharge_amount, outOrderNo);

		console.log("系统", originalParam.context.osName);

		if (originalParam.context.osName == 'android') {
			const datam = JSON.stringify({
				"skuList": [{
					"skuId": "1",
					"price": recharge_amount,
					"quantity": 1,
					"title": "金豆充值",
					"imageList": ["https://dummyimage.com/234x60"],
					"type": 401,
					"tagGroupId": "tag_group_7272625659888041996"
				}],
				"outOrderNo": outOrderNo,
				"totalAmount": recharge_amount,
				"payExpireSeconds": 3000,
				"orderEntrySchema": {
					"path": "components/rechargelist/rechargelist"
				}
			})
			// const  datam =
			// 	'{"skuList":[{"skuId":"1","price":100,"quantity":1,"title":"金豆充值","imageList":["https://dummyimage.com/234x60"],"type":401,"tagGroupId":"tag_group_7272625659888041996"}],"outOrderNo":"NO23112212071168836377684","totalAmount":100,"payExpireSeconds":3000,"orderEntrySchema":{"path":"components/rechargelist/rechargelist"}';
			res.datam = JSON.parse(datam)


			res.byteAuthorization = getByteAuthorization(privateKeyPath, datam, appId, nonceStr, timestamp,
				keyVersion);
			console.log(res.byteAuthorization);


		} else {
			const datam = JSON.stringify({
				"skuList": [{
					"skuId": "1",
					"price": recharge_amount,
					"quantity": 1,
					"title": "金豆充值",
					"imageList": ["https://dummyimage.com/234x60"],
					"type": 401,
					"tagGroupId": "tag_group_7272625659888041996"
				}],
				'payScene': 'IM',
				"outOrderNo": outOrderNo,
				"totalAmount": recharge_amount,
				"payExpireSeconds": 3000,
				"orderEntrySchema": {
					"path": "components/rechargelist/rechargelist"
				}
			})
			// const  datam =
			// 	'{"skuList":[{"skuId":"1","price":100,"quantity":1,"title":"金豆充值","imageList":["https://dummyimage.com/234x60"],"type":401,"tagGroupId":"tag_group_7272625659888041996"}],"outOrderNo":"NO23112212071168836377684","totalAmount":100,"payExpireSeconds":3000,"orderEntrySchema":{"path":"components/rechargelist/rechargelist"}';
			res.datam = JSON.parse(datam)


			res.byteAuthorization = getByteAuthorization(privateKeyPath, datam, appId, nonceStr, timestamp,
				keyVersion);
			console.log(res.byteAuthorization);

		}






		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}